<template>
  <div class="Items">
    <Header :zIndex="0" ref="Header"></Header>
    <div class="content-wrap">
      <center id="app" class="clearfix">
        <div class="top">
          <ul class="daohang_list">
            <li>
              <router-link class="list_item" :to="{ path: '/Create' }">创建活动</router-link>
            </li>
            <li>
              <router-link class="list_item on" :to="{ path: '/Manage' }">投票管理</router-link>
            </li>
            <li>
              <router-link class="list_item" :to="{ path: '/Level' }">账户升级</router-link>
            </li>
            <li>
              <router-link class="list_item" :to="{ path: '/Userinfo' }">个人中心</router-link>
            </li>
            <li>
              <router-link class="list_item" :to="{ path: '/Invate' }">推荐有奖</router-link>
            </li>
          </ul>
        </div>
        <!-- 选手管理 -->
        <div class="right">
          <div class="rank clearfix">
            <span class="font20">排序:</span>
            <el-select v-model="orderType" clearable placeholder="请选择" @change="search" size="small">
              <el-option label="报名时间" :value="3">报名时间</el-option>
              <el-option label="票数" :value="2">票数</el-option>
              <el-option label="编号" :value="1">编号</el-option>
            </el-select>
            <span class="font20" style="margin-left:10px">状态:</span>
            <el-select v-model="status" clearable placeholder="请选择" @change="search" size="small">
              <el-option label="全部" :value="0">全部</el-option>
              <el-option label="审核中" :value="1">审核中</el-option>
              <el-option label="已审核" :value="2">已审核</el-option>
            </el-select>
            <div class="search_player_box">
              <el-input placeholder="请输入选手号或名称" v-model="name" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
              </el-input>
            </div>
          </div>
          <div class="tite">
            <div>
              <span>活动名称:</span>{{actTitle}}
            </div>
            <div class="topbtns">
              <el-button @click="qrcodeShade" type="primary" plain icon="el-icon-link">活动二维码</el-button>
              <div class="imp_btn">
                <el-upload action="" :http-request="importPlayers" :multiple="false" :show-file-list="false" accept=".xls,.xlsx">
                  <el-button slot="trigger" icon="el-icon-upload2" type="success" plain>批量导入选手</el-button>
                </el-upload>
                <el-link type="primary" href="https://static.jdytp.com/file/moban.zip" icon="el-icon-document">下载批量导入模板</el-link>
              </div>
              <el-button @click="exportData" icon="el-icon-download" type="warning" plain>导出数据</el-button>
              <el-button @click="showAddFlag(1)" type="danger" icon="el-icon-circle-plus-outline">添加选手</el-button>
            </div>
          </div>
          <ul class="player_list">
            <li style="position: relative" v-for="(item,index) in itemList" :key="index">
              <div class="img_box">
                <div class="bianhao">编号:{{item.serial}}</div>
                <img v-if="item.cover" :src="item.cover" />
                <iframe v-if="!item.cover && item.video" frameboder="0" allowfullscreen="yes" scrolling="no" :src="item.video"></iframe>
              </div>
              <div class="xm">
                <p>名称：{{item.name}}</p>
                <p>手机号：{{item.phone}}</p>
                <p style="color:#E6A23C;font-size:10px" v-if="item.limit>0">限制投票到：{{formatDate(item.limit)}}</p>
              </div>
              <div class="player_info_box">
                <div class="player_item" style="margin-right: 38px">
                  <p style="color: rgb(149, 64, 244)">{{item.ticket}}</p>
                  <p class="ps">投票数</p>
                </div>
                <div class="player_item">
                  <p style="color: rgb(69, 108, 240)">{{item.pageView}}</p>
                  <p class="ps">浏览量</p>
                </div>
              </div>
              <div class="group_id">
                <span v-if="item.group == ''" style="font-size: 14px;">未分组</span>
                <span v-if="item.group != ''" style="font-size: 14px;">{{item.group}}</span>
              </div>
              <div class="btnbox_outer">
                <div class="player_btnbox">
                  <el-button @click="editItems(item)" icon="el-icon-edit-outline">编辑</el-button>
                  <el-button @click="delItems(item.id)" icon="el-icon-delete">删除</el-button>
                  <el-button @click="verify(item.id)" icon="el-icon-s-check" :disabled="item.state == 1" :style="item.state==0 ? 'color:#f00' : ''">{{item.state==1?'已审核':'待审核'}}</el-button>
                  <el-button @click="votelog(item.id)" :disabled="item.state==0" icon="el-icon-date">投票日志</el-button>
                </div>
                <div class="player_btnbox">
                  <el-button icon="el-icon-chat-line-square" @click="showReplyList(item.id)">评论管理</el-button>
                  <el-button :disabled="item.limit>0" icon="el-icon-lock" @click="voteLimit(item.id)">限制投票</el-button>
                </div>
              </div>
              <img src="../assets/img/yi.png" alt="" class="shenhetype" v-if="item.state == 1" />
              <img src="../assets/img/weisheng.png" alt="" class="shenhetype" v-if="item.state == 0" />
            </li>
            <el-empty :image-size="200" v-if="itemList.length == 0"></el-empty>
          </ul>
          <el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="recordCount" v-if="itemList.length > 0">
          </el-pagination>
        </div>
      </center>
    </div>
    <Footer></Footer>
    <div class="addItem" v-if="showAdd">
      <div class="alert_con">
        <h1>{{editTitle}}</h1>
        <span class="alert_close" title="关闭" @click="showAddFlag"><i class="el-icon-close"></i></span>
        <el-form label-width="100px" v-model="itemData">
          <el-form-item label="选手编号">
            <el-input-number :min="1" :max="500" v-model="itemData.serial" placeholder="请输入选手编号"></el-input-number>
          </el-form-item>
          <el-form-item label="选手名称">
            <el-input v-model="itemData.name" placeholder="请输入选手名称"></el-input>
          </el-form-item>
          <el-form-item label="副标题">
            <el-input v-model="subTitle" placeholder="留空则不展示，展示在选手名称下方"></el-input>
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="itemData.phone" placeholder="请输入选手手机号(手机号保密状态，仅供与主办方联系)"></el-input>
          </el-form-item>
          <el-form-item label="分组" v-if="groupData && groupData.length > 0">
            <el-cascader ref="cascader" v-model="selGroups" :options="cascaderData" :props="{ checkStrictly: true }" clearable style="width: 100%" @change="cascaderSelectChange">
            </el-cascader>
          </el-form-item>
          <el-form-item label="选手图片">
            <el-upload action="" list-type="picture-card" :limit="imgnub" multiple accept=".jpg,.png,.jpeg" :on-remove="removeImage" :before-upload="beforeUploadImage" :http-request="uploadImage" :on-exceed="onImageExceed" :file-list="fileList">
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog>
              <img width="100%" src="" alt="">
            </el-dialog>
          </el-form-item>
          <el-form-item label="选手简介">
            <div style="height: 300px;">
              <vue-ueditor-wrap v-model="itemData.info" :config="editorConfig"></vue-ueditor-wrap>
            </div>
          </el-form-item>
          <el-form-item label="选手音频">
            <el-upload action="" :before-upload="beforeUploadAudio" :http-request="uploadAudio" accept="audio/mp3" :on-remove="mediaRemove" :file-list="audioList" :limit="1">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传MP3文件，且不超过30M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="选手视频">
            <el-row>
              <el-col :span="12">
                <el-radio-group v-model="videoType">
                  <el-radio-button :label="1">本地上传</el-radio-button>
                  <el-radio-button :label="2">视频链接</el-radio-button>
                </el-radio-group>
              </el-col>
              <el-col :span="12">
                <div v-if="videoType == 2">
                  <el-input v-model="itemData.video" placeholder="请输入B站或腾讯视频链接"></el-input>
                  <div>
                    <a href="/Helper?id=6" class="el-upload__tip" target="_blank">如何获取视频链接？</a>
                  </div>
                </div>
                <div v-else-if="videoType == 1">
                  <el-upload action="" accept="video/mp4" :before-upload="beforeUploadVideo" :http-request="uploadVideo" :on-remove="mediaRemove" :file-list="videoList" :limit="1">
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传MP4文件，且不超过50M</div>
                  </el-upload>
                </div>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item v-for="(item, index) in itemData.items" :key="index" :label="item.name">
            <el-input v-model="item.value" :placeholder="'请输入' + item.name"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addItem" icon="el-icon-edit">保存</el-button>
            <el-button @click="showAddFlag">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-dialog title="二维码" width="500px" :visible.sync="qrcodeShow" center class="wxshade">
      <div class="con">
        <div id="qrcodeOut" class="qrcode">
          <vue-qr :text="qrcodeUrl" :size="300"></vue-qr>
        </div>
        <p>链接地址</p>
        <input type="text" id="qrcodeUrl" v-model="qrcodeUrl" readonly>
        <p style="font-size:14px;color:#666"> 点击活动修改，可调整优化活动的界面样式，规则介绍等</p>
        <div @click="copyQrcodeUrl" class="fuzhi">复制</div>
      </div>
    </el-dialog>
    <el-dialog title="限制投票" width="300px" :visible.sync="showLimitDlg">
      <el-form :label-width="80">
        <el-form-item label="限制时长">
          <el-input-number v-model="limitHour" :min="1" :max="24"></el-input-number>
          小时
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="showLimitDlg = false">取 消</el-button>
        <el-button type="primary" @click="submitVoteLimit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Toast } from 'vant'
import Oss from '../../utils/oss'
import User from '../../utils/user'
import Ajax from '../../utils/ajax'
import Footer from '../components/Footer.vue'
import Header from '../components/Header.vue'
import VueUeditorWrap from 'vue-ueditor-wrap'
import vueQr from 'vue-qr'
import Export from '../../utils/export'
import * as XLSX from 'xlsx'

export default {
  name: 'Items',
  components: {
    Header,
    Footer,
    VueUeditorWrap,
    vueQr
  },
  data() {
    return {
      editTitle: '添加选手',
      content: '',
      orderType: 3,
      status: 0,
      name: '',
      code: '',
      tempId: '',
      videoType: 2,
      form: {},
      showAdd: false,
      addFlag: true,
      currentPage: 1,
      pageSize: 20,
      recordCount: 0,
      actTitle: '',
      itemData: {},
      editorOption: {},
      fileList: [],
      itemList: [],
      delmedias:[],
      editId: 0,
      enrollInfo: {},
      selGroups: [],
      groupData: [],
      cascaderData: [],
      qrcodeShow: false,
      qrcodeTitle: '',
      qrcodeImg: '',
      qrcodeUrl: '',
      snStart: '',
      editorConfig: {
        UEDITOR_HOME_URL: '/UEditor/',
        serverUrl: Ajax.serverUrl + '/common/uedit',
        initialFrameHeight: 240,
        autoHeightEnabled: false
      },
      videoList: [],
      audioList: [],
      imgnub: 6,
      userInfo: {},
      showLimitDlg: false,
      limitPlayer: 0,
      limitHour: 0,
      subTitle: ''
    }
  },
  created() {
    if (this.$route && this.$route.query) {
      if (this.$route.query.code) {
        this.code = this.$route.query.code
      } else {
        Toast('参数错误')
        this.$router.back(-1)
      }
      if (this.$route.query.title) {
        this.actTitle = this.$route.query.title
      }
      if (this.$route.query.tempId) {
        this.tempId = this.$route.query.tempId
      }
    } else {
      this.$router.back(-1)
    }
    this.setTitle('选手管理')
    //将s改成l
    var ccn = localStorage.getItem('ccn')
    var cid = localStorage.getItem('vcid')
    this.editorConfig.headers = {
      ccn: ccn,
      cid: cid,
      token: encodeURIComponent(User.getToken())
    }

    this.userInfo = User.getInfo()
    this.getItems()
    this.getEnrollInfo()
  },
  methods: {
    search() {
      this.currentPage = 1
      this.getItems()
    },
    onEditorChange(e) {
      this.itemData.desc = e.html
    },
    getEnrollInfo() {
      Ajax.get('activity/enroll/' + this.code)
        .then((res) => {
          if (res.code == 0) {
            this.enrollInfo = res.data
            this.qrcodeUrl =
              res.data.mpdomain +
              '/' +
              this.tempId +
              '/index.html?act=' +
              this.code
          } else {
            Toast(res.msg)
          }
        })
        .catch((err) => {
          console.error(err)
        })
      Ajax.get('activity/groups/' + this.code)
        .then((res) => {
          if (res.code == 0) {
            this.groupData = res.data
            this.parseGroup(0)
          }
        })
        .catch((err) => {
          console.error(err)
        })
    },
    votelog(id) {
      if (this.userInfo.level < 3) {
        this.$alert('该功能只对企业版及以上会员开放', { type: 'warning' })
        return
      }
      this.$router.push({
        path: '/VoteData',
        query: {
          code: this.code,
          player: id
        }
      })
    },
    showReplyList(id) {
      //评论管理
      this.$router.push({
        path: '/Reply',
        query: {
          code: this.code,
          player: id
        }
      })
    },
    voteLimit(id) {
      //限制投票
      this.limitHour = 2
      this.limitPlayer = id
      this.showLimitDlg = true
    },
    submitVoteLimit() {
      const that = this

      that
        .$confirm(
          '限制后无法撤销，确定要吗？',
          `确定要限制该选手${that.limitHour}小时内不能投票吗？`,
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true
          }
        )
        .then(() => {
          Ajax.post('activity/lock/player', {
            actId: that.code,
            player: that.limitPlayer,
            hour: that.limitHour
          })
            .then((res) => {
              that.showLimitDlg = false
              if (res.code == 0) {
                that.$alert('提交成功')
                that.getItems()
              } else {
                that.$alert(res.msg)
              }
            })
            .catch((err) => {
              console.error(err)
              that.showLimitDlg = false
              that.$alert('网络错误，提交失败')
            })
        })
        .catch(() => {
          console.log('取消')
        })
    },
    exportData() {
      //导出选手数据
      Export.exportPlayers(this.code)
    },
    isNum(n) {
      if (!n) return false
      if (isNaN(n)) return false
      var reg = /^\d+$/gi
      return reg.test(n)
    },
    importPlayers(file) {
      //导入选手数据
      if (file.file) {
        const that = this
        const reader = new FileReader()
        reader.onload = function (e) {
          try {
            var data = e.target.result
            var workbook = XLSX.read(data, { type: 'array' })
            var sheetName = workbook.SheetNames[0]
            var ws = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName])
            var players = []
            for (var i in ws) {
              var item = ws[i]
              var p = { id: 0 }
              for (var j in item) {
                if (j.indexOf('编号') >= 0) {
                  if (that.isNum(item[j])) {
                    p.serial = parseInt(item[j])
                  } else {
                    p.serial = i + 1
                  }
                } else if (j.indexOf('名称') >= 0) {
                  p.name = item[j]
                } else if (j.indexOf('手机') >= 0) {
                  p.phone = item[j]
                } else if (j.indexOf('分组') >= 0) {
                  p.group = item[j]
                } else if (j.indexOf('简介') >= 0) {
                  p.info = item[j]
                } else if (j.indexOf('照片') >= 0) {
                  p.covers = ['/image/' + that.code + '/' + item[j]]
                } else if (j.indexOf('视频') >= 0) {
                  p.video = item[j]
                }
                else if (j.indexOf('副标题') >= 0) {
                  var subTitle = item[j]
                  if (subTitle.trim() != '') {
                    if (!p.items) {
                      p.items = []
                    } 
                    p.items.push({ name: 'subtitle', value: subTitle })
                  }
                }
              }
              if (!p.name || p.name == '') {
                that.$alert('选择名称不能为空', { type: 'error' })
                return
              }
              players.push(p)
            }
            that.uploadPlayers(players)
          } catch (err) {
            console.error(err)
            that.$alert('读取文件失败', { type: 'error' })
          }
        }
        reader.readAsArrayBuffer(file.file)
      }
    },
    uploadPlayers(ary) {
      if (ary && ary.length > 0) {
        Ajax.post('activity/batch/update/player/' + this.code, ary)
          .then((res) => {
            if (res.code == 0) {
              this.$alert('选手导入成功', { type: 'success' })
              this.getItems()
            } else {
              this.$alert('导入失败：' + res.msg, { type: 'error' })
            }
          })
          .catch((err) => {
            console.error(err)
            this.$alert('网络错误，导入失败')
          })
      }
    },
    parseGroup(p, obj) {
      var r = this.groupData.filter((x) => x.parentid == p)
      if (r && r.length > 0) {
        r.sort((a, b) => {
          return a.sort - b.sort
        })
        if (p == 0) {
          this.cascaderData = []
          obj = this.cascaderData
        } else {
          obj.children = []
          obj = obj.children
        }
        r.forEach((val, idx, arr) => {
          var op = {
            value: val.id,
            label: val.name,
            children: null
          }
          obj.push(op)
          this.parseGroup(val.id, op)
        }, this)
      }
    },
    showAddFlag(e) {

      this.delmedias = [];
      if (e === 1) {        
        this.videoList = [];
        this.audioList = [];
        this.fileList = []
        this.itemData = {
          serial: this.snStart
        }
        this.selGroups = []
        this.editId = 0
        this.itemData.info = this.content
        this.subTitle = ''
        this.editTitle = '添加选手'
      }

      if (this.showAdd === false) {
        this.showAdd = true
      } else {
        this.showAdd = false
      }
      this.addFlag = true
    },
    beforeUploadAudio(file) {
      const isAudio = file.type === 'audio/mpeg'
      const isLt30M = file.size / 1024 / 1024 <= 30
      if (!isAudio) {
        this.$alert('上传视频只支持MP4格式!')
      }
      if (!isLt30M) {
        this.$alert('上传视频大小不能超过 30MB!')
      }
      return isAudio && isLt30M
    },
    beforeUploadVideo(file) {
      const isVideo = file.type === 'video/mp4'
      const isLt50M = file.size / 1024 / 1024 <= 50
      if (!isVideo) {
        this.$alert('上传视频只支持MP4格式!')
      }
      if (!isLt50M) {
        this.$alert('上传视频大小不能超过 50MB!')
      }
      return isVideo && isLt50M
    },
    beforeUploadImage(file) {
      const isIMAGE = file.type === 'image/jpeg' || 'image/gif' || 'image/png'
      const isLt1M = file.size / 1024 / 1024 < 3
      if (!isIMAGE) {
        this.$alert('上传文件只能是图片格式!')
      }
      if (!isLt1M) {
        this.$alert('上传文件大小不能超过 3MB!')
      }
      return isIMAGE && isLt1M
    },
    uploadImage(file) {
      return this.uploadOneFile(file.file, 'image')
    },
    removeImage(file) {
      if (file.key) {
        Oss.remove(file.key, function (err, data) {
          console.log(err, data)
        })
      }
      this.fileList = this.fileList.filter((x) => {
        return x.key != file.key
      })
    },
    onImageExceed(e) {
      this.$alert('最多只允许上传6张图片')
    },
    uploadAudio(file) {
      return this.uploadOneFile(file.file, 'audio')
    },
    uploadVideo(file) {
      return this.uploadOneFile(file.file, 'video')
    },
    uploadOneFile(file, type) {
      if (!type) type = 'image'
      var fileName = this.getRemoteName(file, type)
      const that = this
      if (type == 'video'){
        that.itemData.video = fileName
      }
      
      Oss.upload(file, fileName, function (err, data) {
        if (!err && data.statusCode == 200) {
          //上传成功
          var key = data.key ? data.key : null
          var loc = data.Location
          if (!key) {
            var n = loc.indexOf('/', 8)
            key = loc.substr(n + 1)
          }
          var name = loc.substr(loc.lastIndexOf('/') + 1)
          loc = 'http://' + loc
          if (type == 'image') {
            that.fileList.push({
              uid: file.uid,
              key: key,
              url: loc,
              status: 'success'
            })
          } else if (type == 'audio') {
            that.itemData.audio = key
            that.audioList.push({
              uid: file.uid,
              key: key,
              url: loc,
              name: name,
              status: 'success'
            })
          } else if (type == 'video') {
            that.itemData.video = key
            that.videoList.push({
              uid: file.uid,
              key: key,
              url: loc,
              name: name,
              status: 'success'
            })
          }
        } else {
          Toast('上传失败')
        }
      })
      return false
    },
    startWith(s, f) {
      if (!s || !f) return false
      var n = s.indexOf(f)
      return n == 0
    },
    addItem() {
      this.addFlag = false
      if (!this.itemData.serial) {
        Toast('请输入选手编号！')
        this.addFlag = true
        return false
      }
      if (!this.itemData.name || this.itemData.name === '') {
        Toast('请输入选手名称！')
        this.addFlag = true
        return false
      }

      var ary = []
      const that = this
      if (this.fileList && this.fileList.length > 0) {
        this.fileList.forEach((val, idx) => {
          if (!that.startWith(val.key, '/')) {
            ary.push('/' + val.key)
          } else {
            ary.push(val.key)
          }
        })
      }

      if (this.groupData && this.groupData.length > 0) {
        if (!this.selGroups || this.selGroups.length == 0) {
          Toast('请选择选手分组')
          return
        }
      }

      this.itemData.covers = ary
      if (this.selGroups && this.selGroups.length > 0) {
        this.itemData.groupId = this.selGroups[this.selGroups.length - 1]
      }

      if (this.subTitle.trim() != '') {
        if (!this.itemData.items) this.itemData.items = []
        this.itemData.items.push({ name: 'subtitle', value: this.subTitle })
      }

      Ajax.post('activity/update/player/' + this.code, this.itemData)
        .then((res) => {
          if (res.code == 0) {
            if (this.editId > 0) {
              Toast('保存成功')
            } else {
              Toast('添加成功')
            }

            this.currentPage = 1
            this.getItems()
            this.itemData = {}
            this.audioList = []
            this.videoList = []
            this.showAdd = false

            if(this.delmedias.length > 0){
              for(var i in this.delmedias) {
                var key = this.delmedias[i];
                console.log(key);
                try {
                  Oss.remove(file.key, function (err, data) {})
                } catch (err2) {}
              }          
            }
            this.delmedias = [];

          } else {
            Toast(res.msg)
          }
        })
        .catch((err) => {
          console.error(err)
        })
    },
    verify(mid) {
      this.$confirm('审核通过页面可以显示，确定通过？', '确定要通过吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          Ajax.get('activity/verify/player/' + this.code + '/' + mid)
            .then((res) => {
              if (res.code == 0) {
                Toast('审核成功')
                this.getItems()
              } else {
                Toast(res.msg)
              }
            })
            .catch((err) => {
              console.error(err)
            })
        })
        .catch(() => {})
    },
    getItems() {
      if (isNaN(this.orderType) || !this.orderType || this.orderType == '')
        this.orderType = 0
      else this.orderType = parseInt(this.orderType)
      if (isNaN(this.status) || !this.status || this.status == '')
        this.status = 0
      else this.status = parseInt(this.status)

      Ajax.get('activity/players/' + this.code, {
        page: this.currentPage,
        size: this.pageSize,
        order: this.orderType,
        state: this.status,
        kw: this.name
      })
        .then((data) => {
          if (data.code === 0) {
            this.itemList = data.data.data
            this.recordCount = data.data.recordCount
            this.snStart = data.data.recordCount + 1
          } else {
            Toast(data.msg)
          }
        })
        .catch((err) => {
          console.error(err)
          Toast('网络错误，获取数据失败')
        })
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.itemList = []
      this.getItems()
    },
    // 删除该活动
    delItems(mid) {
      this.$confirm('删除后将不可恢复！确定删除？', '确定要删除该么？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          Ajax.delete('activity/delete/player?act=' + this.code + '&id=' + mid)
            .then((res) => {
              if (res.code == 0) {
                Toast('删除成功')
                this.getItems()
              } else {
                Toast(res.msg)
              }
            })
            .catch((err) => {
              console.error(err)
              Toast('网络错误，操作失败')
            })
        })
        .catch(() => {})
    },
    findGroups(obj, g) {
      if (!obj || g <= 0) return
      var tar = this.groupData.filter((x) => {
        return x.id == g
      })
      if (tar && tar.length > 0) {
        obj.splice(0, 0, tar[0].id)
        this.findGroups(obj, tar[0].parentid)
      }
    },
    editItems(item) {
      const that = this
      this.subTitle = ''
      this.delmedias = [];
      Ajax.get('activity/player/info/' + this.code + '/' + item.id)
        .then((res) => {
          if (res.code == 0) {
            this.itemData = res.data
            if (!this.itemData.items) {
              this.itemData.items = []
            }
            this.itemData.items.forEach((val, idx, ary) => {
              if (val.name == 'subtitle') {
                that.subTitle = val.value
              }
            })
            this.itemData.items = this.itemData.items.filter(
              (x) => x.name != 'subtitle'
            )

            this.selGroups = []
            this.findGroups(this.selGroups, res.data.groupId)

            this.fileList = []
            if (res.data.covers) {
              res.data.covers.forEach((v, i) => {
                this.fileList.push({
                  key: v,
                  url: res.data.cdn + v,
                  status: 'success'
                })
              })
            }
            this.audioList = []
            if (res.data.audio) {
              var ak = res.data.audio
              if (ak.indexOf('/') == 0) ak = ak.substr(1)
              var name = ak.substr(ak.lastIndexOf('/') + 1)
              this.audioList.push({
                key: res.data.audio,
                url: res.data.cdn + res.data.audio,
                name: name,
                status: 'success'
              })
            }
            this.videoList = []
            if (res.data.video) {
              var ak = res.data.video
              if (ak.indexOf('http://') == 0 || ak.indexOf('https://') == 0) {
                //网络视频
                this.videoType = 2
              } else {
                if (ak.indexOf('/') == 0) ak = ak.substr(1)
                var name = ak.substr(ak.lastIndexOf('/') + 1)
                this.videoList.push({
                  key: res.data.video,
                  url: res.data.cdn + res.data.video,
                  name: name,
                  status: 'success'
                })
              }
            }
            this.editTitle = '编辑选手'
            this.editId = res.data.id
            this.addFlag = true
            this.showAdd = true
          } else {
            Toast(res.msg)
          }
        })
        .catch((err) => {
          console.error(err)
          Toast('获取选手信息失败')
        })
    },
    qrcodeShade() {
      this.qrcodeShow = true
    },
    copyQrcodeUrl() {
      var Url = document.getElementById('qrcodeUrl')
      Url.select()
      document.execCommand('Copy')
      Toast('复制成功~！')
    },
    mediaRemove(file, fileList) {
      if (file.key) {
        if(this.delmedias.length == 0){
          this.delmedias = [];
        }        
        this.delmedias.push(file.key);
        // try {
        //   Oss.remove(file.key, function (err, data) {})
        // } catch (err2) {}
      }
      

      if (file.url.indexOf('.mp3') > 0) {
        this.audioList = []
        this.itemData.audio = ''
      } else {
        this.itemData.video = ''
        this.videoList = []
      }
    },
    cascaderSelectChange() {
      // 自动收到下拉框
      this.$refs.cascader.dropDownVisible = false
    }
  },
  watch: {
    selGroups(newVal, oldVal) {
      console.log(newVal, oldVal)
    }
  }
}
</script>
<style src="@/assets/css/items.css" scoped></style>